package com.oreilly.ez.fileserver.web;

import com.oreilly.ez.fileserver.base.LoginUser;
import com.oreilly.ez.fileserver.base.R;
import com.oreilly.ez.fileserver.util.Const;
import com.oreilly.ez.fileserver.util.JwtUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * used for login
 */

@Api
@CrossOrigin
@RestController
public class LoginCtrl {




    @PostMapping("/login")
    public Object login(@RequestBody LoginUser loginUser, HttpServletResponse response) {

        Assert.notNull(loginUser, "passcode missing");
        String passcode = loginUser.getPasscode();
        Assert.notNull(passcode, "passcode not null");

        String[] codes = Const.get();
        for (String code : codes) {
            if(StringUtils.equals(code, passcode)){

                String token = JwtUtil.create(passcode);

                //set cookie
                Cookie cookie = new Cookie("x-token", token);

                // 1 day
                cookie.setMaxAge(24*60*60);
                cookie.setHttpOnly(true);
                response.addCookie(cookie);

                Map<String, Object> map = new HashMap<>();
                map.put("token", token);

                return R.ok(map);
            }
        }

        return R.err("invalid passcode");
    }
}
